package com.benshou.bcss.common.validation;

import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

/**
 * 参数校验器包装器
 * <p>
 *     用于将校验异常结果转化为 {@link ConstraintViolationException} 后抛出（如有）。
 * </p>
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 * @see ConstraintViolationException
 */
@RequiredArgsConstructor
public class ValidatorWrapper {

    /**
     * 参数校验器
     */
    @NonNull
    private final Validator validator;

    /**
     * 校验参数，如有不通过的，抛出异常。
     *
     * @param validationTarget 校验目标
     * @param validationGroups 列表：校验组
     * @throws ConstraintViolationException 参数校验不通过时，抛出此异常
     */
    public void validateThrowing(
            Object validationTarget,
            Class<?>... validationGroups) throws ConstraintViolationException {
        var validationResults = this.validator.validate(validationTarget, validationGroups);
        if (validationResults == null || validationResults.isEmpty()) {
            return;
        }

        throw new ConstraintViolationException(validationResults);
    }
}
